package com.yeshine.opendata.api;

import com.yeshine.opendata.api.model.Session;

import javax.servlet.ServletContextEvent;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by taohj on 2014/9/23.
 */
public class Test implements javax.servlet.ServletContextListener {



    private Map<String, Session> sessionContainer;


    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("==============会话容器初始化===============");
        sessionContainer=new HashMap<String, Session>();
       /* Timer timer = new Timer(sessionContainer);
        Thread thread = new Thread(timer);
        thread.start();*/

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("==============会话容器销毁===============");
    }
}


class Timer implements Runnable {

    private static int index = 0;

    private Map<String, Session> sessionContainer = new HashMap<String, Session>();

    public Timer(Map<String, Session> sessionContainer) {
        this.sessionContainer = sessionContainer;
    }

    @Override
    public void run() {


        while (true) {


            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("第" + ++index + "次,扫描会话容器");

            Iterator<Map.Entry<String, Session>> iterator = this.sessionContainer.entrySet().iterator();

            while (iterator.hasNext()) {
                Map.Entry<String, Session> entry = iterator.next();
                String key = entry.getKey();

                Session session = entry.getValue();
                Date now = new Date();
                if ((now.getTime() - session.getLastTime().getTime()) / 10000 > 6) {

                    iterator.remove();
                    System.out.println("会话：--" + session + "--" + "已超时");

                } else {
                    System.out.println("会话:" + session + "在线");
                }
            }


        }
    }
}

